<?php
namespace app\admin\controller;

use app\admin\model\Authorizer;
use app\admin\model\Category;
use app\wechat\controller\Index;
use app\wechat\controller\Platform;
use EasyWeChat\Kernel\Exceptions\HttpException;
use think\Db;
use think\Exception;
use think\facade\Log;

class Template extends Base
{
    // 模板消息首页
    public function index()
    {
        $wechat = new Index();
        $turl = $wechat->get_preauth_url();
        $this->assign('turl', $turl); // 授权地址
        return $this->fetch('template/index');
    }

    //获取分类列表
    public function get_category()
    {
        $pid = $this->request->post('pid', 0);
        // 通过父id获取分类
        $catregory = Category::where(['delstatus' => 1, 'pid' => $pid])->select();
        return $catregory;
    }

    // 获取已授权账号列表
    public function get_authorizer_list()
    {
        $keyword = $this->request->post('keyword');
        $category = $this->request->post('category', '');
        $category2 = $this->request->post('category2', '');
        // 判断分类
        if ($category !== '') {
            $map[] = ['category', '=', $category];
        }
        if ($category2 !== '') {
            $map[] = ['category2', '=', $category2];
        }
        $map[] = ['delstatus', '=', 1];
        // 获取列表,并遍历取得分类名称
        $list = Authorizer::where($map)->whereLike('name|ghid', '%' . $keyword . '%')->limit(15)->select();
        foreach ($list as $v) {
            $v->category = Category::where('id', $v->category)->value('categoryname');
            $v->category2 = Category::where('id', $v->category2)->value('categoryname');
        }
        return $list;
    }

    // 设置模板消息界面
    public function set_temp_view()
    {
        $appid = $this->request->param('appid');
        $this->assign('appid', $appid);
        return $this->fetch('template/set_temp');
    }

    // 获取该公众号下的所有模板消息
    public function get_template_list()
    {
        $appid = $this->request->post('appid');
        $auth = Authorizer::get(['appid' => $appid]);
        $platform = new Platform();

        // 调用查询模板消息接口
        try {
            $gh = $platform->getGhWithToken($appid, $auth->refresh_token);
            $templates = $gh->template_message->getPrivateTemplates();
            if (array_key_exists('errcode', $templates)) {
                // 返回错误
                return $this->api_resp_error($this->handle_errcode($templates['errcode']));
            } else if (array_key_exists('template_list', $templates)) {
                // 遍历处理模板消息
                $titles = array();
                $list = array();
                foreach ($templates['template_list'] as $template) {
                    array_push($titles, array('value' => $template['template_id'], 'label' => $template['title']));
                    $list[$template['template_id']] = $template;
                }
                $data['gh_name'] = $auth->name;
                $data['titles'] = $titles;
                $data['template_list'] = $list;
                return $this->api_result('success', $data);
            }
        } catch (HttpException $exception) {
            return $this->api_resp_error('账号未授权');
        }
    }

    public function templateInfo()
    {
        $wechat = new Index();
        $turl = $wechat->get_preauth_url();
        $this->assign('turl',$turl);
        return $this->fetch('template/templateInfo');
    }

    // 获取账号列表
    public function getAccountList()
    {
        $keyword = $this->request->post('keyword');
        $authorizer_list = Authorizer::where('name|ghid', 'like', '%' . $keyword . '%')->where('delstatus', 1)->limit(10)->select();
//        $list = Db::table('nx_template_account')
//            ->where('wechatname|ghid','like','%'.$keyword.'%')
//            ->where(['delstatus'=>'1','type'=>$type])
//            ->select();
        return $this->api_resp_success('','',$authorizer_list);
    }
    public function doAddAccount()
    {
        $ids = $this->request->post('ids');
        $reapet = Db::table('nx_template_account')->where('authid','in',$ids)->select();
        if($reapet){
            $info = '';
            foreach ($reapet as $key=>$val){
                $info = $info.$val['wechatname'].'，';
            }
            $info = $info.' 已存在';
            return $this->api_resp_error($info);
        }
        $list = Db::table('nx_authorizer')->where('id','in',$ids)->select();
        foreach ($list as $k=>$v){
            $data = [
                'authid'=>$v['id'],
                'wechatname'=>$v['name'],
                'ghid'=>$v['ghid'],
                'appid'=>$v['appid'],
                'type'=>1,
                'createtime'=>date('Y-m-d H:i:s',time())
            ];
            $res = Db::name('nx_template_account')->insert($data);
        }
        return $this->api_resp_success('添加成功','',$res);
    }
    public function sendServiceTemplate()
    {
        $aid = $this->request->param('aid');
        $appid = Db::table('nx_authorizer')->where('id',$aid)->field('appid')->find();
        $this->assign('appid',$appid['appid']);
        return $this->fetch('template/sendServiceTemplate');
    }
    public function getTencentList()
    {
        $this->checklogin();
        $keyword = $this->request->post('keyword','');
        $map[] = ['delstatus', '=', 1];
        $list = Db::table('nx_authorizer')
            ->where('name|ghid','like','%'.$keyword.'%')
            ->where($map)
            ->order('category','desc')
            ->select();
        foreach($list as $k=>$v){
            if($v['category']!=''){
                $categorylist = Db::table('nx_category')->where('id',$v['category'])->find();
                $list[$k]['category'] = $categorylist['categoryname'];
                if($categorylist){
                    $catregory2 = Db::table('nx_category')->where('id',$v['category2'])->find();
                    $list[$k]['category2'] = $catregory2['categoryname'];
                }
            }else{
                $list[$k]['category'] = '';
                $list[$k]['category2'] = '';
            }
        }
        return  $this->api_resp_success("",'',$list);
    }
    public function doDeletelAccount()
    {
        $ids = $this->request->post('ids');
        $res = Db::name('nx_template_account')->where('id','in',$ids)->update(['delstatus'=>4]);
        if($res){
            return $this->api_resp_success('','',$res);
        }
    }
    public function editAccount()
    {
        $aid = $this->request->param('aid');
        $data = Db::table('nx_template_account')->where('id',$aid)->find();
        $this->assign('data',$data);
        return $this->fetch('template/editAccount');
    }
    public function doEditAccount()
    {
        $name = $this->request->post('name');
        $ghid = $this->request->post('ghid');
        $appid = $this->request->post('appid');
        $appsecret = $this->request->post('appsecret');
        $id = $this->request->post('aid');
        $data = [
            'wechatname'=>$name,
            'ghid'=>$ghid,
            'appid'=>$appid,
            'appsecret'=>$appsecret,
            'updatetime'=>date('Y-m-d H:i:s',time())
        ];
        $res = Db::name('nx_template_account')->where('id',$id)->update($data);
        if($res){
            return $this->api_resp_success('','',$res);
        }
    }
    public function setTemplate()
    {
        $aid = $this->request->param('aid');
        $data = Db::table('nx_template_account')->where('id',$aid)->find();
        $this->assign('data',$data);
        return $this->fetch('template/setTemplate');
    }
    public function doSetTemplate()
    {
        $dataarr = $this->request->param();
        if($dataarr['type'] == '1'){
            $data = [
                'accountid'=>$dataarr['id'],
                'type'=>$dataarr['type'],
                'content_detail'=>$dataarr['content'],
                'color_detail'=>$dataarr['color_content'],
                'appointment_time'=>$dataarr['apptime'],
                'color_apptime'=>$dataarr['color_apptime'],
                'appointment_place'=>$dataarr['place'],
                'color_place'=>$dataarr['color_place'],
                'appointment_user'=>$dataarr['user'],
                'color_user'=>$dataarr['color_user'],
                'reason'=>$dataarr['reason'],
                'color_reason'=>$dataarr['color_reason'],
                'remark'=>$dataarr['remark'],
                'color_remark'=>$dataarr['color_remark'],
                't_url'=>$dataarr['t_url'],
                'createtime'=>date('Y-m-d H:i:s',time())
            ];
        }else if($dataarr['type'] == '2'){
            $data = [
                'type'=>$dataarr['type'],
                'accountid'=>$dataarr['id'],
                'begin_time'=>$dataarr['begin'],
                'color_begin'=>$dataarr['color_begin_2'],
                'color_remark'=>$dataarr['color_remark'],
                'remark'=>$dataarr['remark'],
                't_url'=>$dataarr['t_url'],
                'appointment_content'=>$dataarr['appiontcontent2'],
                'color_content'=>$dataarr['appiont_content_2'],
                'content_detail'=>$dataarr['content'],
                'color_detail'=>$dataarr['color_content'],
                'createtime'=>date('Y-m-d H:i:s',time())
            ];
        }else if($dataarr['type'] == '3'){
            $data = [
                'type'=>$dataarr['type'],
                'accountid'=>$dataarr['id'],
                'begin_time'=>$dataarr['begin'],
                'color_begin'=>$dataarr['color_begin_2'],
                'color_remark'=>$dataarr['color_remark'],
                'remark'=>$dataarr['remark'],
                't_url'=>$dataarr['t_url'],
                'appointment_content'=>$dataarr['appiontcontent2'],
                'color_content'=>$dataarr['appiont_content_2'],
                'content_detail'=>$dataarr['content'],
                'color_detail'=>$dataarr['color_content'],
                'createtime'=>date('Y-m-d H:i:s',time())
            ];
        }
        $exist = Db::table('nx_template_content')->where('accountid',$dataarr['id'])->find();
        if($exist){
            $res = Db::name('nx_template_content')->where('accountid',$dataarr['id'])->update($data);
        }else{
            $res = Db::name('nx_template_content')->insert($data);
        }
        if($res){
            return $this->api_resp_success('','',$res);
        }
    }
    public function sendTemplate()
    {
        $id = $this->request->param('aid');
        $data = Db::table('nx_template_content')->where('id',$id)->find();
        $this->assign('data',$data);
        return $this->fetch('template/sendTemplate');
    }
    public function serviceInfo()
    {
        return $this->fetch('template/serviceInfo');
    }
}
